package com.example.multiaccountfetcher.controller;

import com.example.multiaccountfetcher.model.AccountRequest;
import com.example.multiaccountfetcher.model.RequestCallback;
import com.example.multiaccountfetcher.model.RequestParams;
import com.example.multiaccountfetcher.queue.RequestQueueManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/data")
@Slf4j
public class DataFetchController {
    
    @Autowired
    private RequestQueueManager requestQueueManager;
    
    // 用于存储请求的CompletableFuture
    private final Map<String, CompletableFuture<ResponseEntity<?>>> requestFutures = new ConcurrentHashMap<>();
    
    /**
     * 拉取数据接口
     */
    @PostMapping("/fetch/{accountId}")
    public CompletableFuture<ResponseEntity<?>> fetchData(
            @PathVariable String accountId,
            @RequestBody RequestParams params,
            @RequestParam(value = "interfaceType", required = false) String interfaceType) {
        
        log.info("Received fetch request for account: {}, params: {}, interfaceType: {}", 
                accountId, params, interfaceType);
        
        CompletableFuture<ResponseEntity<?>> future = new CompletableFuture<>();
        requestFutures.put(accountId + System.nanoTime(), future);
        
        // 创建请求回调
        RequestCallback callback = new RequestCallback() {
            @Override
            public void onSuccess(String accId, Object result) {
                log.info("Data fetch successful for account: {}", accId);
                Map<String, Object> responseBody = new HashMap<>();
                responseBody.put("success", true);
                responseBody.put("accountId", accId);
                responseBody.put("data", result);
                future.complete(ResponseEntity.ok(responseBody));
            }
            
            @Override
            public void onFailure(String accId, String error) {
                log.error("Data fetch failed for account: {}, error: {}", accId, error);
                Map<String, Object> responseBody = new HashMap<>();
                responseBody.put("success", false);
                responseBody.put("accountId", accId);
                responseBody.put("error", error);
                future.complete(ResponseEntity.status(500).body(responseBody));
            }
        };
        
        // 创建并提交请求
        AccountRequest request = new AccountRequest();
        request.setAccountId(accountId);
        request.setRequestTime(null); // 会在RequestQueueManager中设置
        request.setParams(params);
        request.setCallback(callback);
        request.setInterfaceType(interfaceType);
        boolean added = requestQueueManager.addRequest(request);
        
        if (!added) {
            Map<String, Object> responseBody = new HashMap<>();
            responseBody.put("success", false);
            responseBody.put("accountId", accountId);
            responseBody.put("error", "System is busy, please try again later");
            future.complete(ResponseEntity.status(503).body(responseBody));
        }
        
        return future;
    }
    
    /**
     * 获取队列状态接口
     */
    @GetMapping("/status")
    public ResponseEntity<RequestQueueManager.QueueStatus> getQueueStatus() {
        RequestQueueManager.QueueStatus status = requestQueueManager.getQueueStatus();
        return ResponseEntity.ok(status);
    }
    
}